const log = require('j7/log');
const bcutils = require('j7/bcutils');
const utils = require('j7/utils');
const bcconst = require('common/bcconst');
const BaseEventProcess = require('../common/BaseEventProcess');
const metaFactory = require('../../../metadata/factory');

class Transfer extends BaseEventProcess {

  async start() {
    const returnValues = this.getReturnValues();
    const from = bcutils.toNormalAddress(returnValues['from']);
    const to = bcutils.toNormalAddress(returnValues['to']);
    const tokenId = returnValues['tokenId'];

    await this.mustBeMint(to, tokenId, bcconst.BC_NFT_HERO);
    if (bcutils.isSysAddress(from)) {
      console.log(tokenId, this.getNetId());
      const airDropMeta = metaFactory.getAirDrop(
        tokenId,
        this.getNetId(),
        bcconst.BC_NFT_HERO,
        this.getContractAddress());
      console.log(airDropMeta);
      if (airDropMeta) {
        await this.apiMint(to, tokenId, airDropMeta);
        await this.adjustHeroId(tokenId);
      } else {
        await this.ingameActivate(from, to, tokenId, bcconst.BC_NFT_HERO);
      }
    } else {
      await this.add721NftRefresh
      (
        this.getNetId(),
        this.getContractAddress(),
        this.getContractName(),
        tokenId
      );
    }
    await this.update721NftOwner(tokenId, this.getContractAddress(), to, from);
    await this.markOk();
  }

  async apiMint(address, tokenId, airDropMeta) {
    console.log('apiMint', address, tokenId, airDropMeta);
    const params = {
      'c': 'Callback',
      'a': 'dispatch',
      'action': 'mintNftHero',
      'address': bcutils.toNormalAddress(address),
      'tokenId': tokenId,
      'itemId': airDropMeta['item_id'],
      'quality': airDropMeta['quality'],
    };
    await this.callGameApi
    (params,
     async (data) => {
        if (!data) {
          this.throwError('callGameApi error:' + data);
        }
        if (data['errcode'] == 0 ||
           data['errcode'] == 1) {
          return true;
        }
       return false;
     });
  }

  async adjustHeroId(tokenId) {
    const logHead = ' adjustHeroId ';
    const {err, row} = await this.gameDbConn(
      'ormSelectOne',
      't_hero',
      [
        ['token_id',  tokenId],
        ['activate',  1],
      ]
    );
    if (err) {
      this.throwError('adjustHeroId:' + err);
    }
    if (row && row['hero_id']) {
      await this.adjustItemId(tokenId, row['hero_id']);
      await this.adjustQuality(tokenId, row['quality']);
    }
  }

}

module.exports = Transfer;
